<?php

namespace app\common\library;

use app\admin\model\Account;
use app\admin\model\Admin;
use app\admin\model\AdminBasicZoom;
use app\admin\model\AdminLog;
use app\admin\model\AuthGroupAccessZoom;
use app\common\model\User;
use app\common\model\UserRule;
use fast\Random;
use think\Config;
use think\Cookie;
use think\Db;
use think\Exception;
use think\Hook;
use think\Request;
use think\Session;
use think\Validate;

class Auth
{
    protected static $instance = null;
    protected $_error = '';
    protected $_logined = false;
    protected $_user = null;
    protected $_token = '';
    //Token默认有效时长
    protected $keeptime = 2592000;
    protected $requestUri = '';
    protected $rules = [];
    //默认配置
    protected $config = [];
    protected $options = [];
    //protected $allowFields = ['id', 'username', 'nickname', 'mobile', 'avatar', 'score'];
    protected $allowFields = ['id', 'username', 'nickname', 'mobile', 'avatar', 'status'];

    public function __construct($options = [])
    {
        if ($config = Config::get('user'))
        {
            $this->config = array_merge($this->config, $config);
        }
        $this->options = array_merge($this->config, $options);
    }

    /**
     *
     * @param array $options 参数
     * @return Auth
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }

        return self::$instance;
    }

    /**
     * 获取User模型
     * @return User
     */
    public function getUser()
    {
        return $this->_user;
    }

    /**
     * 兼容调用user模型的属性
     *
     * @param string $name
     * @return mixed
     */
    public function __get($name)
    {
        return $this->_user ? $this->_user->$name : null;
    }

    /**
     * 根据Token初始化
     *
     * @param string $token Token
     * @return boolean
     */
    public function init($token)
    {
        if ($this->_logined) {
            return true;
        }
        if ($this->_error) {
            return false;
        }
        $data = Token::get($token);  // pr('----'. $data. '---',1);
        if (!$data) {
            return false;
        }
        $user_id = intval($data['user_id']);
        if ($user_id > 0) {
            //$user = User::get($user_id);                        //获取admin表的所有数据
            $user = User::get(['id'=>$user_id]);
            if (!$user) {
                $this->setError('Account not exist');
                return false;
            }
            if ($user['status'] != 'normal') {
                $this->setError('Account is locked');
                return false;
            }
            $this->_user = $user;
            $this->_logined = true;
            $this->_token = $token;

            //初始化成功的事件
            Hook::listen("user_init_successed", $this->_user);

            // 当expiretime不为0时，延长token失效时间（永不失效的token为后端登录后创建的，用于会议配置接口的访问，解决以往使用session常失效的问题。后台个人资料的登出所有设备功能可以清除此token）
            $db_token = Token::getDbToken($token);
            if ($data['expiretime'] > 0) {
                Db::name('user_token')->where(['token'=>$db_token,'user_id'=>$data['user_id'],'createtime'=>$data['createtime']])->update(['expiretime'=>(time()+$this->keeptime)]);
            }

            return true;
        } else {
            $this->setError('You are not logged in');
            return false;
        }
    }

    /**
     * 注册用户
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param array  $extend   扩展参数
     * @return boolean
     */
    public function register($username, $password, $email = '', $mobile = '', $extend = [])
    {
        // 检测用户名、昵称、邮箱、手机号是否存在
        if (User::getByUsername($username)) {
            $this->setError('Username already exist');
            return false;
        }
        if (User::getByNickname($username)) {
            $this->setError('Nickname already exist');
            return false;
        }
        if ($email && User::getByEmail($email)) {
            $this->setError('Email already exist');
            return false;
        }
        if ($mobile && User::getByMobile($mobile)) {
            $this->setError('Mobile already exist');
            return false;
        }

        $ip = request()->ip();
        $time = time();

        $data = [
            'username' => $username,
            'password' => $password,
            'email'    => $email,
            'mobile'   => $mobile,
            'level'    => 1,
            'score'    => 0,
            'avatar'   => '',
        ];
        $params = array_merge($data, [
            'nickname'  => preg_match("/^1[3-9]{1}\d{9}$/",$username) ? substr_replace($username,'****',3,4) : $username,
            'salt'      => Random::alnum(),
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal'
        ]);
        $params['password'] = $this->getEncryptPassword($password, $params['salt']);
        $params = array_merge($params, $extend);

        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try {
            $user = User::create($params, true);
            //$this->_user = User::get($user->id);
            $this->_user = User::get(['id'=>$user->id]);

            //设置Token
            $this->_token = Random::uuid();
            Token::set($this->_token, $user->id, $this->keeptime);

            //设置登录状态
            $this->_logined = true;

            //注册成功的事件
            Hook::listen("user_register_successed", $this->_user, $data);
            Db::commit();
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
        return true;
    }

    /*
     * 查找用户基本信息表中有无此用户
     */
    public function isAdminBasic($account_id){
        if(empty($account_id)){
            $this->setError('login is incorrect');
            return false;
        }

        $admin_basic = Admin::get(['account_id'=>$account_id]);//查找admin_id
        $r = $admin_basic->toArray();
        if(!$r){
            $this->setError('无法查到此用户');
            return false;
        }
        $admin_id = $r['id'];
        $this->chkGroupAcsZoom($admin_id);
        $exist = AdminBasicZoom::where('admin_id', $admin_id)->where('account_id', $account_id)->find();
        if(empty($exist)){
            $basic_admin['account_id'] = $account_id;
            $basic_admin['admin_id'] = $admin_id;
            $basic_admin['serial'] = selfserial();
            $basic_admin['avatar'] = config('default_avatar');
            $basic_admin['ctime'] = time();
            $basic_admin['source'] = Account::USER_SOURCE_99;;
            $basic_admin['joinip'] = request()->ip(0,false);
            $basic_admin['loginip'] = request()->ip(0,false);

            $admin_basic =  new AdminBasicZoom();//注册用户基本信息表
            $admin_basic_r = $admin_basic->save($basic_admin);
            if (!$admin_basic_r){
                $this->error('用户基本信息注册失败，请重试', null, ['token' => $this->request->token()]);
                return false;
            }
            return $admin_basic->id;
        }else{
           return  $exist->id;
        }

    }

    /*
     * 检查举办人的权限是否存在 不存在，则成为举办人权限
     */
     public function chkGroupAcsZoom($admin_id){
        $map['uid'] = $admin_id;
       // $map['group_id'] = AuthGroupAccessZoom::SPONSOR;
        $admin_count = Db::name('auth_group_access_zoom')
            ->where($map)
            ->count();

        if (!$admin_count){//当没有举办人的权限时加入举办的角色
            $aga_result = AuthGroupAccessZoom::create(['uid'=>$admin_id, 'group_id'=>AuthGroupAccessZoom::SPONSOR]);
            if ($aga_result === false) {
                $this->error('检查用户权限错误，请重试', null, ['token' => $this->request->token()]);
            }
        }
        unset($map);
        return true;
    }


    /**
     * 账号登录
     *
     * @param   string $username 用户名
     * @param   string $password 密码
     * @param   int $keeptime 有效时长
     * @return  boolean
     */
    public function accountLogin($username, $password, $keeptime = 0)
    {
        $account = Account::get(['mobile|username' => $username]);

        if (!$account) {
            $this->setError('Username is incorrect');
            return false;
        }

        $bid = $this->isAdminBasic($account->id);
        if(!$bid){
            $this->setError('Username is incorrect');
            return false;
        }

        $admin_basic = AdminBasicZoom::get($bid);//基本信息表

        if (Config::get('fastadmin.login_failure_retry') && $admin_basic->loginfailure >= 10 && time() - $admin_basic->utime < 300) {
            $this->setError('Please try again after 5 minute');
            return false;
        }


        if ($account->password != md5(md5($password) . $account->salt)) {
            $admin_basic->loginfailure++;
            $this->setError('Password is incorrect');
            return false;
        }

        $admin_basic->loginfailure = 0;

        $admin_basic->save();
        $account->token_zoom = zoom_token();
        $account->token = $account->token_zoom;
        $account->save();
        $account = $account->toArray();

        $r = $admin_basic->toArray();

        $r['id'] = $account['id'];
        $r['username'] = $account['username'];
        $r['nickname'] = $account['nickname'];
        $r['mobile'] = $account['mobile'];
        $r['createtime'] = $account['createtime'];
        $r['updatetime'] = $account['updatetime'];
        $r['token'] = $account['token_zoom'];
        Session::set("account", $r);
        Session::push1('account', 'keeplogin', $keeptime);
        return true;
    }
    /**
     * 用户登录
     *
     * @param string $account  账号,用户名、邮箱、手机号
     * @param string $password 密码
     * @return boolean
     */
    public function login($account, $password)
    {
        $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
        $user = User::get([$field => $account]);
        if (!$user) {
            $this->setError('Account is incorrect');
            return false;
        }

        if ($user->status != 'normal') {
            $this->setError('Account is locked');
            return false;
        }
        if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
            $this->setError('Password is incorrect');
            return false;
        }

        //直接登录会员
        $this->direct($user->id);

        return true;
    }

    /*
     * 二次admin session
     */
    public function admin_session($admin_id){

        $admin_basic = AdminBasicZoom::get(['admin_id'=>$admin_id]);
        $admin_basic->loginip = request()->ip(0,false);
        $admin_basic->save();
        //$admin = Admin::get($admin_id);//后台户信息表
        $admin = Admin::get(['id'=>$admin_id]);

        $account = Session::pull('account');
        if ($account){
            $admin->token_zoom = $account['token'];
            $admin->token = $admin->token_zoom;
        }else{
            $admin->token_zoom = zoom_token();
            $admin->token = $admin->token_zoom;
        }
        $admin->save();
        // 查出角色id和角色类型
        $group_info = Db::name('auth_group_access_zoom')->alias('aga')
            ->join('auth_group_zoom ag', 'aga.group_id = ag.id')
            ->where('aga.uid', $admin_id)
            ->field('aga.group_id, ag.type')
            ->find();
        $admin_session = $admin->toArray();
        $admin_session['group_id']   = $group_info['group_id'];
        $admin_session['group_type'] = $group_info['type'];

        Session::set("admin", $admin_session);
        $this->keeplogin(1);

        // 加入后台token记录
        $this->setToken($admin->token_zoom, $admin_id, 1);
        $this->_logined = true;
        return true;
    }

    /**
     * 管理员登录
     * @param   string $username 用户名
     * @param   string $password 密码
     * @param   int $admin_id 当前登录用户id
     * @param   int $keeptime 有效时长
     * @return  boolean
     */
    /**
     */
    public function admin_login($username, $password, $admin_id, $keeptime = 0,$loginip='')
    {
        //$admin = Admin::get(['id'=>$admin_id]);
        $admin_basic = AdminBasicZoom::get(['admin_id'=>$admin_id]);
        if (!$admin_basic) {
            $this->setError('Username is incorrect');
            return false;
        }
        if ($admin_basic->status == 'hidden') {
            $this->setError('Admin is forbidden');
            return false;
        }

        /* if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
            $this->setError('Please try again after 1 day');
            return false;
        }
        if ($admin->password != md5(md5($password) . $admin->salt)) {
            $admin->loginfailure++;
            $admin->save();
            $this->setError('Password is incorrect');
            return false;
        }
        $admin->loginfailure = 0; */

        //$admin->loginip = $this->request->header("host");
        $admin_basic->loginip = $loginip;
        $l = date('Y-m-d', $admin_basic->logintime-(86400 * 15));
        $p = date('Y-m-d', $admin_basic->prevtime);
        if($l <= $p){
            // 连续登录
            $admin_basic->successions += 1;
            if($admin_basic->successions>$admin_basic->maxsuccessions){
                $admin_basic->maxsuccessions = $admin_basic->successions;
            }
        }else{
            // 非连续登录
            if($admin_basic->successions>$admin_basic->maxsuccessions){
                $admin_basic->maxsuccessions = $admin_basic->successions;
            }
            $admin_basic->successions = 1;
        }
        $admin_basic->prevtime = $admin_basic->logintime;
        $admin_basic->logintime = time();
        $admin_basic->device ='mac';//这儿需要获取设备号
        $admin_basic->logincount += 1;
        $admin_basic->save();
        // $admin->token = Random::uuid();

        // 添加每次登录的设备
//        $user_agent = $this->request->header()["user-agent"];
//        if (preg_match('/Windows/', $user_agent)){
//            $admin->loginEquipment = "win";
//        }elseif (preg_match('/Macintosh/', $user_agent)){
//            $admin->loginEquipment = "mac";
//        }else{
//            $admin->loginEquipment = "win";
//        }


        //$admin = Admin::get($admin_id);//后台户信息表
        $admin = Admin::get(['id'=>$admin_id]);
        $account = Session::pull('account');
        if ($account){
            $admin->token_zoom = $account['token'];
            $admin->token = $admin->token_zoom;
        }else{
            $admin->token_zoom = zoom_token();
            $admin->token = $admin->token_zoom;
        }
        $admin->save();
        // 查出角色id和角色类型
        $group_info = Db::name('auth_group_access_zoom')->alias('aga')
            ->join('auth_group_zoom ag', 'aga.group_id = ag.id')
            ->where('aga.uid', $admin_id)
            ->field('aga.group_id, ag.type')
            ->find();
        $admin_session = $admin->toArray();
        $admin_session['group_id']   = $group_info['group_id'];
        $admin_session['group_type'] = $group_info['type'];

        Session::set("admin", $admin_session);
        $this->keeplogin($keeptime);

        // 加入后台token记录
        $this->setToken($admin->token_zoom, $admin_id, $keeptime);
        $this->_logined = true;
        return true;
    }

    /**
     * 获取加密后的Token
     * @param string $token Token标识
     * @return string
     */
    protected function getEncryptedToken($token) {
        $config = \think\Config::get('token');
        return hash_hmac($config['hashalgo'], $token, $config['key']);
    }

    /**
     * 存储Token
     * @param   string $token Token
     * @param   int $user_id 会员ID
     * @param   int $expire 过期时长,0表示无限,单位秒
     * @return bool
     */
    public function setToken($token, $user_id, $expire = null) {
        // $expiretime = !is_null($expire) && $expire !== 0 ? time() + $expire : 0;
        $encryptedToken = $this->getEncryptedToken($token);

        $check_token = Db::name('user_token')->where(['user_id'=>$user_id, 'expiretime'=>$expire])->field('user_id,expiretime')->find();
        if (empty($check_token)) {
            Db::name('user_token')->insert([
                'token'      => $encryptedToken,
                'user_id'    => $user_id,
                'createtime' => time(),
                'expiretime' => $expire,
                'tokenbu'    => $token
            ]);
        }
    }
    /**
     * 刷新保持登录的Cookie
     *
     * @param   int $keeptime
     * @return  boolean
     */
    public function keeplogin($keeptime = 0)
    {
        if ($keeptime) {
            $expiretime = time() + $keeptime;
            $key = md5(md5($this->id) . md5($keeptime) . md5($expiretime) . $this->token);
            $data = [$this->id, $keeptime, $expiretime, $key];
            Cookie::set('keeplogin', implode('|', $data), 86400 * 15);
            return true;
        }
        return false;
    }
    /**
     * 退出
     *
     * @return boolean
     */
    public function logout()
    {
        if (!$this->_logined) {
            $this->setError('You are not logged in');
            return false;
        }
        //设置登录标识
        $this->_logined = false;
        //删除Token
        Token::delete($this->_token);
        //退出成功的事件
        Hook::listen("user_logout_successed", $this->_user);
        return true;
    }

    /**
     * 退出登录
     */
    /*public function logout()
    {
        $admin = Admin::get(intval($this->id));
        if ($admin) {
            //$admin->token = '';
            $admin->token_zoom = '';
            $admin->save();
        }
        $this->logined = false; //重置登录状态
        //删除Token
        Token::delete($this->_token);
        Cookie::delete("keeplogin");
        //退出成功的事件
        Hook::listen("user_logout_successed", $this->_user);
        return true;
    }*/

    /**
     * 修改密码
     * @param string $newpassword       新密码
     * @param string $oldpassword       旧密码
     * @param bool   $ignoreoldpassword 忽略旧密码
     * @return boolean
     */
    public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
    {
        if (!$this->_logined) {
            $this->setError('You are not logged in');
            return false;
        }
        //判断旧密码是否正确
        if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
            Db::startTrans();
            try {
                $salt = Random::alnum();
                $newpassword = $this->getEncryptPassword($newpassword, $salt);
                $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);

                Token::delete($this->_token);
                //修改密码成功的事件
                Hook::listen("user_changepwd_successed", $this->_user);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->setError($e->getMessage());
                return false;
            }
            return true;
        } else {
            $this->setError('Password is incorrect');
            return false;
        }
    }

    /**
     * 自动登录
     * @return boolean
     */
    public function autologin()
    {
        $keeplogin = Cookie::get('keeplogin');
        if (!$keeplogin) {
            return false;
        }
        list($id, $keeptime, $expiretime, $key) = explode('|', $keeplogin);
        if ($id && $keeptime && $expiretime && $key && $expiretime > time()) {
            //$admin = Admin::get($id);
            $admin = Admin::get(['id'=>$id]);
            if (!$admin || !$admin->token_zoom) {
                return false;
            }
            //token有变更
            if ($key != md5(md5($id) . md5($keeptime) . md5($expiretime) . $admin->token_zoom)) {
                return false;
            }
            Session::set("admin", $admin->toArray());
            //刷新自动登录的时效
            $this->keeplogin($keeptime);
            return true;
        } else {
            return false;
        }
    }
    /*
     * 手机号注册
     */

    public function mobile_register($mobile){
        // 开启事务
        Db::startTrans();
        try{
            // 处理数据
            $params = [];
            $params['username'] = $mobile;
            $params['nickname'] = $mobile;
            $params['password'] = 123456;
            $params['username'] = $mobile;
            $params['salt'] = pwdSalt();
            $params['password'] =  md5(md5($params['password']) . $params['salt']);
            $params['createtime'] = time(); //创建时间为当前时间
            $params['updatetime'] = time(); //更新时间为当前时间
            $params['serial'] = selfserial();
            $params['avatar'] = config('default_avatar');
            $params['joinip'] = request()->ip(0,false);
            $params['loginip'] = request()->ip(0,false);
            $params['token_zoom'] = zoom_token();//来自zoom表中的token
            $params['username'] = $params['mobile'];
            $params['source'] = Account::USER_SOURCE_99;//用户来源 99 代表onzoom用户

            $account_field = Db::name('account')->getTableFields();
            $account_params = array_filter(array_intersect_key($params, array_flip($account_field)));

            $account_id = Db::name('account')->insertGetId($account_params);
            if (!$account_id){
                $this->error(__('注册失败，请重试'), ['token' => $this->request->token()], 0);
            }


            //3、创建admin用户
            $admin_field = Db::name('admin')->getTableFields();
            $admin_params = array_filter(array_intersect_key($params, array_flip($admin_field)));
            $admin_params['account_id'] = $account_id;

            $admin = new Admin();
            $result_admin = $admin->save($admin_params);
            if (!$result_admin){
                $this->error('注册失败，请重试', null, ['token' => $this->request->token()]);
            }

            //4 创建Zoom用户基本信息表
            $basic_admin['account_id'] = $account_id;
            $basic_admin['admin_id'] = $admin['id'];
            $basic_admin['serial'] = $params['serial'];
            $basic_admin['avatar'] = $params['avatar'];
            $basic_admin['ctime'] = time();
            $basic_admin['source'] = $params['source'];
            $basic_admin['joinip'] = $params['joinip'];
            $basic_admin['loginip'] = $params['loginip'];

            $admin_basic =  new AdminBasicZoom();//注册用户基本信息表
            $admin_basic_r = $admin_basic->save($basic_admin);
            if (!$admin_basic_r){
                $this->error('用户基本信息注册失败，请重试', null, ['token' => $this->request->token()]);
            }

            $map['uid'] = $admin['id'];
            $admin_count = Db::name('auth_group_access_zoom')
                ->where($map)
                ->count();

            if (!$admin_count){//当没有举办人的权限时加入举办的角色
                $aga_result = AuthGroupAccessZoom::create(['uid'=>$admin['id'], 'group_id'=>AuthGroupAccessZoom::SPONSOR]);
                if ($aga_result === false) {
                    $this->error(model('AuthGroupAccessZoom')->getError());
                }
            }

            Db::commit();
        }catch (\Exception $e){
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        AdminLog::setTitle(__('Login'));

        $r = $admin_basic->toArray();

        $r['id'] = $account_id;
        $r['username'] = $params['username'];
        $r['nickname'] = $params['nickname'];
        $r['mobile'] = $params['mobile'];
        $r['createtime'] = $params['createtime'];
        $r['updatetime'] = $params['updatetime'];
        $r['token'] = $params['token_zoom'];

        Session::set("account", $r);
        Session::push1('account', 'keeplogin',0);

        $admin = Admin::get(['account_id'=>$account_id]);//后台户信息表

        // 查出角色id和角色类型
        $group_info = Db::name('auth_group_access_zoom')->alias('aga')
            ->join('auth_group_zoom ag', 'aga.group_id = ag.id')
            ->where('aga.uid', $admin->id)
            ->field('aga.group_id, ag.type')
            ->find();
        $admin_session = $admin->toArray();
        $admin_session['group_id']   = $group_info['group_id'];
        $admin_session['group_type'] = $group_info['type'];

        Session::set("admin", $admin_session);
        $this->keeplogin(0);

        // 加入后台token记录
        $this->setToken($admin->token_zoom, $admin->id, 0);
        $this->_logined = true;
        unset($r);
        unset($admin_basic);
        unset($map);
        unset($basic_admin);
        unset($params);
        return true;
    }

    /*
     * 用户手机号直接登录
     */
    public function mobile_direct($user_id){
        $account = Account::get($user_id);

        if (!$account) {
            $this->setError('Username is incorrect');
            return false;
        }
        $account->token_zoom = zoom_token();
        $account->save();
        $account = $account->toArray();

        $bid = $this->isAdminBasic($user_id);
        if(!$bid){
            $this->setError('Username is incorrect');
            return false;
        }

        $admin_basic = AdminBasicZoom::get(['account_id'=>$user_id]);//基本信息表
        $admin_basic->loginip = request()->ip();
        $admin_basic->source = $account->source;
        $admin_basic->prevtime = $admin_basic->logintime;
        $admin_basic->logintime =  time();
        $admin_basic->successions =  $admin_basic->successions + 1;
        $admin_basic->maxsuccessions = max($admin_basic->successions, $admin_basic->maxsuccessions);
        $admin_basic->logincount = $admin_basic->logincount +1;
        $admin_basic->save();

        $r = $admin_basic->toArray();

        $r['id'] = $account['id'];
        $r['username'] = $account['username'];
        $r['nickname'] = $account['nickname'];
        $r['mobile'] = $account['mobile'];
        $r['createtime'] = $account['createtime'];
        $r['updatetime'] = $account['updatetime'];
        $r['token'] = $account['token_zoom'];
        Session::set("account", $r);
        Session::push1('account', 'keeplogin',0);

        $admin = Admin::get(['account_id'=>$account['id']]);//后台户信息表
        $account = Session::pull('account');
        if ($account){
            $admin->token_zoom = $account['token'];
           // $admin->token = $admin->token_zoom;
        }else{
            $admin->token_zoom = zoom_token();
           // $admin->token = $admin->token_zoom;
        }
        $admin->save();
        // 查出角色id和角色类型
        $group_info = Db::name('auth_group_access_zoom')->alias('aga')
            ->join('auth_group_zoom ag', 'aga.group_id = ag.id')
            ->where('aga.uid', $admin->id)
            ->field('aga.group_id, ag.type')
            ->find();
        $admin_session = $admin->toArray();
        $admin_session['group_id']   = $group_info['group_id'];
        $admin_session['group_type'] = $group_info['type'];

        Session::set("admin", $admin_session);
        $this->keeplogin(0);

        // 加入后台token记录
        $this->setToken($admin->token_zoom, $admin->id, 0);
        $this->_logined = true;
        unset($r);
        unset($admin_basic);
        return true;
    }
    /**
     * 直接登录账号
     * @param int $user_id
     * @return boolean
     */
    public function direct($user_id)
    {
        //$user = User::get($user_id);
        $user = User::get(['id' => $user_id]);
        if ($user) {
            Db::startTrans();
            try {
                $ip = request()->ip();
                $time = time();

                //判断连续登录和最大连续登录
                if ($user->logintime < \fast\Date::unixtime('day')) {
                    $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
                    $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
                }

                $user->prevtime = $user->logintime;
                //记录本次登录的IP和时间
                $user->loginip = $ip;
                $user->logintime = $time;
                //重置登录失败次数
                $user->loginfailure = 0;

                $user->save();

                $this->_user = $user;

                $this->_token = Random::uuid();
                Token::set($this->_token, $user->id, $this->keeptime);

                $this->_logined = true;

                //登录成功的事件
                Hook::listen("user_login_successed", $this->_user);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->setError($e->getMessage());
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检测是否是否有对应权限
     * @param string $path   控制器/方法
     * @param string $module 模块 默认为当前模块
     * @return boolean
     */
    public function check($path = null, $module = null)
    {
        if (!$this->_logined) {
            return false;
        }

        $ruleList = $this->getRuleList();
        $rules = [];
        foreach ($ruleList as $k => $v) {
            $rules[] = $v['name'];
        }
        $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
        $url = strtolower(str_replace('.', '/', $url));
        return in_array($url, $rules) ? true : false;
    }

    /**
     * 判断是否登录
     * @return boolean
     */
    public function isLogin()
    {
        if ($this->_logined) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前Token
     * @return string
     */
    public function getToken()
    {
        return $this->_token;
    }

    /**
     * 获取会员基本信息
     */
   /* public function getUserinfo()
    {
        $data = $this->_user->toArray();
        $allowFields = $this->getAllowFields();
        $userinfo = array_intersect_key($data, array_flip($allowFields));
        $userinfo = array_merge($userinfo, Token::get($this->_token));
        return $userinfo;
    }*/

    /**
     * 获取会员组别规则列表
     * @return array
     */
    public function getRuleList()
    {
        if ($this->rules) {
            return $this->rules;
        }
        $group = $this->_user->group;
        if (!$group) {
            return [];
        }
        $rules = explode(',', $group->rules);
        $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
        return $this->rules;
    }

    /**
     * 获取当前请求的URI
     * @return string
     */
    public function getRequestUri()
    {
        return $this->requestUri;
    }

    /**
     * 设置当前请求的URI
     * @param string $uri
     */
    public function setRequestUri($uri)
    {
        $this->requestUri = $uri;
    }

    /**
     * 获取允许输出的字段
     * @return array
     */
    public function getAllowFields()
    {
        return $this->allowFields;
    }

    /**
     * 设置允许输出的字段
     * @param array $fields
     */
    public function setAllowFields($fields)
    {
        $this->allowFields = $fields;
    }

    /**
     * 删除一个指定会员
     * @param int $user_id 会员ID
     * @return boolean
     */
    public function delete($user_id)
    {
        //$user = User::get($user_id);
        $user = User::get(['id'=> $user_id]);
        if (!$user) {
            return false;
        }
        Db::startTrans();
        try {
            // 删除会员
            User::destroy($user_id);
            // 删除会员指定的所有Token
            Token::clear($user_id);

            Hook::listen("user_delete_successed", $user);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
        return true;
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return boolean
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return false;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }

    /**
     * 设置会话有效时间
     * @param int $keeptime 默认为永久
     */
    public function keeptime($keeptime = 0)
    {
        $this->keeptime = $keeptime;
    }

    /**
     * 渲染用户数据
     * @param array  $datalist  二维数组
     * @param mixed  $fields    加载的字段列表
     * @param string $fieldkey  渲染的字段
     * @param string $renderkey 结果字段
     * @return array
     */
    public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
    {
        $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
        $ids = [];
        foreach ($datalist as $k => $v) {
            if (!isset($v[$fieldkey])) {
                continue;
            }
            $ids[] = $v[$fieldkey];
        }
        $list = [];
        if ($ids) {
            if (!in_array('id', $fields)) {
                $fields[] = 'id';
            }
            $ids = array_unique($ids);
            $selectlist = User::where('id', 'in', $ids)->column($fields);
            foreach ($selectlist as $k => $v) {
                $list[$v['id']] = $v;
            }
        }
        foreach ($datalist as $k => &$v) {
            $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
        }
        unset($v);
        return $datalist;
    }

    /**
     * 设置错误信息
     *
     * @param $error 错误信息
     * @return Auth
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? __($this->_error) : '';
    }

    /**
     * 验证用户是否和公司存在注册关联
     */
    public function checkUserCompany($account_id = '', $company_serial=''){
        if (!$account_id) {
            return FALSE;
        }else{
            if ($company_serial) {
                $usercompany = Db::name('admin')
                    ->alias('a')
                    ->join('company cy', 'a.company_id = cy.id')
                    ->where(['a.account_id'=>$account_id, 'cy.serial'=>$company_serial])
                    ->field('a.id')->find();
            }else{
                $usercompany = Db::name('admin')
                    ->alias('a')
                    ->join('company cy', 'a.company_id = cy.id')
                    ->where(['a.account_id'=>$account_id, 'a.status'=>'normal'])
                    ->where('a.id = cy.owner')
                    ->field('a.id')->find();
            }

            if (!empty($usercompany)) {
                return TRUE;
            }else{
                return FALSE;
            }
        }
    }

    /*
     *  获取token
     */
    public function getRefreshtoken($user_id){
        $this->direct($user_id);
        return $this->_token;
    }


    // ----------------------------------------- niuxitong 2021-01-24 ---------------------------
    /**
     * 用户登录一
     *
     * @param string    $account    账号,用户名、手机号
     * @param string    $password   密码
     * @param string    $login_type 登录类型，login代表密码登录/captchalogin代表验证码登录
     * @return boolean
     */
    public function loginAccountNew($account, $password = '', $login_type){
        $accountuser = Db::name('account')
            ->where('username', '=', $account)
            ->field('id,password,salt,status,logintime,successions,maxsuccessions,loginCount,isOld,source')
            ->find();

        if (empty($accountuser)) {
            $this->setError('账号不存在');
            return FALSE;
        }
        //TODO 这里用不到 公司信息
        $usercompanylist = [];
        if ($accountuser['status'] != 'normal') {
            $this->setError('账号已被锁定');
            return FALSE;
        }
        if ($login_type == 'login') {
            $encryptpwd = $this->getEncryptPassword($password, $accountuser['salt']);
            if ($accountuser['password'] != $encryptpwd) {
                $this->setError('密码不正确');
                return FALSE;
            }
        }

        $ip = request()->ip();
        $time = time();
        //判断连续登录和最大连续登录
        //successions  连续登陆天数
        //maxsuccessions  最大连续登录天数
        //operationtime 执行操作时间
        if ($accountuser['logintime'] < \fast\Date::unixtime('day')) {
            // 如果是一天中的第一次登陆，就更新这两个值（确保这两个值一天只更新一次。）
            $data['successions'] = $accountuser['logintime'] < \fast\Date::unixtime('day', -1) ? 1 : $accountuser['successions'] + 1;
            $data['maxsuccessions'] = max($accountuser['successions'], $accountuser['maxsuccessions']);
        }
        $data['prevtime'] = $accountuser['logintime'];
        //记录本次登录的IP和时间
        $data['loginip'] = $ip;
        $data['logintime'] = $time;
        // 记录到执行操作时间
        $data['operationtime'] = $time;
        $data['loginCount'] = $accountuser['loginCount'] + 1;
        $ret = Db::name('account')->where(['id'=>$accountuser['id']])->update($data);
        //注意，到这里并没有更新 token 字段
        $this->_token = Random::uuid();
        Token::set($this->_token, 'accountid_'.$accountuser['id'], $this->keeptime);
        return ['account_id'=>$accountuser['id'], 'token'=>$this->_token, 'company_list'=>$usercompanylist];
    }

    /**
     * 用户登录
     * @param string  $account      账号,用户名、邮箱、手机号
     * @param string $loginEquipment  设备
     * @param int $accountid  account_id
     * @param string $token
     * @return bool
     * @throws Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function loginNew($account, $loginEquipment, $accountid, $token)
    {
        $user = Admin::get(['username'=>$account, 'account_id'=>$accountid]);
        if (!$user) {
            $this->setError('账号不存在');
            return FALSE;
        }
        if ($user->status != 'normal') {
            $this->setError('账户已经被锁定');
            return FALSE;
        }

        $ip = request()->ip();
        $time = time();
        //判断连续登录和最大连续登录
        if ($user->logintime < \fast\Date::unixtime('day')) {
            $data['successions'] = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
            $data['maxsuccessions'] = max($user->successions, $user->maxsuccessions);
        }
        $data['loginEquipment'] = $loginEquipment;       // 设置当前登录设备信息
        $data['prevtime'] = $user->logintime;
        //记录本次登录的IP和时间
        $data['loginip'] = $ip;
        $data['logintime'] = $time;
        //记录到执行操作时间
        $data['operationtime'] = $time;
        $data['loginCount'] = $user->loginCount + 1;
        $ret = Db::name('admin')->where(['id'=>$user->id])->update($data);
        Session::delete('admin');
        Session('userInfo', $user->toArray());     //这里为了兼容后面的调用， 其实不能写到session里 TODO 后期优化
        //直接登录
        $this->directNew($user->id, $token);
        return TRUE;
    }

    /**
     * 直接登录账号  (此方法更新了user_token表的信息)
     * @param int $user_id
     * @return boolean
     */
    public function directNew($user_id, $token)
    {
        //$user = Admin::get($user_id);
        $user = Admin::get(['id'=>$user_id]);
        if ($user)
        {
            $ip = request()->ip();
            $time = time();
            //判断连续登录和最大连续登录
            if ($user->logintime < \fast\Date::unixtime('day')) {
                $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
                $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
            }
            $user->prevtime = $user->logintime;
            //记录本次登录的IP和时间
            $user->loginip = $ip;
            $user->logintime = $time;
            // 记录到执行操作时间
            $user->operationtime = $time;
            //再次更新 admin表
            $user->save();
            $this->_user = $user;
            $this->_token = $token;         //Random::uuid();
            Token::delete($this->_token);   //清除之前的token
            //清除原userid对应的token，以达到互踢效果
            Token::clear($user->id);                                //全部清空user_token表中 user_id = $user->id的记录。
            Token::set($this->_token, $user->id, $this->keeptime);  //重新设置一条记录到 user_token表中   ///  TODO  这里有问题， 写进去的不一样。
            $this->_logined = TRUE;
            //登录成功的事件
            Hook::listen("user_login_successed", $this->_user);
            return TRUE;
        }else{
            return FALSE;
        }
    }

    /**
     * 获取用户登录信息
     * niuxitong
     */
    public function getUserinfo()
    {
        $data = $this->_user->toArray();
        $allowFields = $this->getAllowFields();
        $userInfo = array_intersect_key($data, array_flip($allowFields)); //返回指定的字段即可
        $userInfo = array_merge($userInfo, Token::get($this->_token));      //把user_token信息合并进去

        //增加其他部分用户信息
        $list = [];
        $user_id = $userInfo['id'];
        $list['id'] = Iden::encrypt($user_id);
        $list['username'] = $userInfo['username'];
        $list['nickname'] = $userInfo['nickname'];
        $list['mobile'] = $userInfo['mobile'];
        $list['status'] = $data['status'];
        $list['token'] = $userInfo['token'];        //注意这里不再是 token_zoom
        $list['tokenbu'] = $userInfo['token'];        //注意这里不再是 token_zoom

        if(!empty($user_id)){
            $admin_basic = AdminBasicZoom::get(['admin_id'=>$user_id]);
            $list['avatar'] = isset($admin_basic['avatar']) ? $admin_basic['avatar']:'';
            $list['intro'] = isset($admin_basic['intro']) ? $admin_basic['intro']:'';
            $list['selftag'] = isset($admin_basic['selftag']) ? $admin_basic['selftag']:'';
            $list['serial'] = isset($admin_basic['serial']) ? $admin_basic['serial']:'';
            $list['company'] = isset($admin_basic['company']) ? $admin_basic['company']:'';
            $list['email'] = isset($admin_basic['email']) ? $admin_basic['email']:'';
            $list['position'] = isset($admin_basic['position']) ? $admin_basic['position']:'';
        }
        return $list;
    }

}
